package com.zcp.controller;

import com.zcp.entity.User;
import com.zcp.result.Result;
import com.zcp.service.UserService;
import com.zcp.utils.VerifyCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class usercontroller {
    @Autowired
    private UserService userService;

//    用户退出
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/back/login.jsp";
    }


    @RequestMapping("login")
    @ResponseBody
    public Result login(String name,String password,String code,HttpSession session){
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        Result result = new Result();
        String imagecode = (String) session.getAttribute("code");
        try{
            if(StringUtils.equalsAnyIgnoreCase(imagecode,code)){
                User user1 = userService.login(user);
                session.setAttribute("user",user1);
                result.setMsg("登录成功");
                result.setStatus(true);
                return result;
            }else {
                throw new RuntimeException("验证码输入错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("登录失败："+e.getMessage());
            return result;
        }

    }



    @RequestMapping("register")
    @ResponseBody
    public Result register(User user,String code, HttpSession session){
        Result result = new Result();
        System.out.println(code);
        try {
            String implode = (String)session.getAttribute("code");

            if(implode.equalsIgnoreCase(code)){
                userService.register(user);
                result.setMsg("注册成功");
                result.setStatus(true);
            }else{
                throw new RuntimeException("验证码输入错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("注册失败："+e.getMessage());
            result.setStatus(false);
        }
        return result;
    }



    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
       String code = VerifyCodeUtils.generateVerifyCode(4);
       session.setAttribute("code",code);
       VerifyCodeUtils.outputImage(250,60,response.getOutputStream(),code);
    }
}
